<template>
  <div>
    <li @dblclick="editItem(todo)">
      <!--      <input type="checkbox" name="matter" id="" v-model="todo.done">-->
      <input type="checkbox" name="matter" id="" @change="checkDone(todo.id)" :checked="todo.done">
      &nbsp;
      <input type="text" ref="inputTitle"  :value="todo.title" class="editIn" v-show="todo.isEdit" @blur="ensureEdit($event,todo)" @keyup.enter="ensureEdit($event,todo)">
      <span class="todoTitle" v-show="!todo.isEdit">{{todo.title}}</span>
      <button class="delete" @click="deleteItem(todo.id)">删除</button>
      <button class="edit" @click="editItem(todo)">编辑</button>
    </li>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
  name: "MyItem",
  props:['todo'],
  methods:{
    deleteItem(id){
      //消息的发布
      if(confirm('确认删除嘛？'))  pubsub.publish("deleteTodo",id)
    },
    checkDone(id){
      //触发公共组件的某个事件
      this.$bus.$emit("checkTodo",id)
    },
    //编辑
    editItem(todo){
      if(!todo.hasOwnProperty("isEdit")){
        this.$set(todo,'isEdit',true)
      }else{
        todo.isEdit=true
      }
      //由于代码是按顺序执行的，所以不会在执行完上面的代码之后就重新渲染页面
      //继续向下执行，但此时的input框还是隐藏状态，隐藏状态是没办法获取焦点的，因此使用定时器来延迟获取焦点
      // setTimeout(()=>{
      //   this.$refs.inputTitle.focus()
      // })

      this.$nextTick(function(){
        this.$refs.inputTitle.focus()
      })
    },
    //失去焦点确认编辑成功
    ensureEdit(e,todo){
      todo.isEdit=false
      if(!e.target.value.trim())  return alert("输入的内容不得为空")
      this.$bus.$emit("editTodo",todo.id,e.target.value)
    }
  }
}
</script>

<style scoped lang="less">
li{
  //height: 35%;
  //width: 96%;
  display: block;
  //background-color: pink;
  margin: auto;
  padding: 12px;
  border-top: 1px solid rgba(87, 87, 87, 0.3);
  //border-left: 1px solid rgba(87, 87, 87, 0.3);
  //border-right: 1px solid rgba(87, 87, 87, 0.3);
  box-sizing: border-box;
  //border-collapse: collapse;
  .editIn{
    font-size: 16px;
    border: 1px solid #ccc;
    padding: 5px;
    border-radius: 4px;
    box-sizing: border-box;
  }
  .editIn:focus{
    border-color: #66afe9;
    box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%), 0 0 8px rgb(102 175 233 / 60%);
    outline: none;
  }
  .delete{
    background-color: #d9534f;
    float: right;
    padding: 3px 10px;
    color: white;
    border: 1px solid #d43f3a;
    border-radius: 5px;
    cursor: pointer;
    &:hover{
      background-color: #c9302c;
      border: 1px solid #ac2925;
    }
  }
  .edit{
    //background-color: #337ab7;
    float: right;
    padding: 3px 10px;
    margin-right: 5px;
    color: white;
    border: 1px solid #4cae4c;
    border-radius: 5px;
    cursor: pointer;
    &:hover{
      border: 1px solid #398439;
      //background-color: #286090;
      background-color: #449d44;
      border-color: #398439;
    }
    background-color: #5cb85c;
    //border-color: #4cae4c;
  }
  &:hover{
    background-color: rgba(0,0,0,0.1);
  }
}
</style>
